﻿using StoryTeller.Domain;
using StoryTeller.Infrastructure.DataAccess.DAL.Base;
using StoryTeller.Infrastructure.DataAccess.Parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StoryTeller.Infrastructure.DataAccess.DAL
{
    public class UserDAL : BaseDAL, IUserDAL
    {
        public void Insert(User entidade)
        {
            entidade.LastLogin = DateTime.Now;

            Entities.User.Add(entidade.ParseDomainToEntity());

            Save();
        }

        public void Update(User entidade)
        {
            EUser usr = Entities.User.First(c => c.Id == entidade.Id);

            usr.LastUpdate = DateTime.Now;

            Save();
        }

        public void Delete(int id)
        {
            EUser cat = Entities.User.First(c => c.Id == id);

            if (cat != null)
            {
                Entities.User.Remove(cat);

                Save();
            }
        }

        public ICollection<User> Select()
        {
            ICollection<EUser> coll = Entities.User.ToList();

            return coll.Select(c => c.ParseEntityToDomain()).ToList();
        }

        public User Select(int id)
        {
            EUser eusr = Entities.User.First(c => c.Id == id);

            if (eusr != null)
                return eusr.ParseEntityToDomain();
            
            return null;
        }

        public User Select(string usrProviderId)
        {
            EUser eusr = Entities.User.FirstOrDefault(c => c.UserIdentity == usrProviderId);

            if (eusr != null)
            {
                eusr.LastLogin = DateTime.Now;

                Save();

                return eusr.ParseEntityToDomain();
            }

            return null;
        }

        public Pagination<User> Select(Pagination<User> pagination)
        {
            pagination.TotalItems = Entities.User.Count();
            var query = from usr in Entities.User
                        where
                            (string.IsNullOrEmpty(pagination.Filter.Name) || usr.Name == pagination.Filter.Name)
                        select usr;

            pagination.List = query.Skip((pagination.PageNumber - 1) * pagination.PageSize).Take(pagination.PageSize).Select(c => c.ParseEntityToDomain()).ToList();

            return pagination;
        }
    }
}
